import time

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.select import Select
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
from util.basedir import basedir



class Base():
    def __init__(self,driver):
        self.driver = driver


    def openurl(self,url):
        self.driver.get(url)

    def loc_ele(self,loc):
        return self.driver.find_element(*loc)

    def loc_eles(self,loc):
        return self.driver.find_elements(*loc)

    #截屏
    def capturepic(self,fillename):
        t = time.strftime("%Y%m%d%H%M%S",time.localtime())
        self.driver.save_screenshot(basedir+r"/data/"+t+fillename)

    def log_wait_ele(self,loc):
        return  WebDriverWait(self.driver,15,1).until(EC.element_to_be_clickable(loc))

    #鼠标方法
    def hoverele(self,loc):
        ele = self.loc_ele(loc)
        ActionChains(self.driver).move_to_element(ele).perform()
    #双击
    def doubleclick(self,loc):
        ele = self.loc_ele(loc)
        ActionChains(self.driver).double_click(ele).perform()
    #右击
    def rightclick(self,loc):
        ele = self.loc_ele(loc)
        ActionChains(self.driver).context_click(ele).click()

    #键盘事件-回车-
    def enter(self,loc):
        ele = self.loc_ele(loc)
        ele.send_keys(Keys.ENTER)

    # 键盘事件-全选
    def selectall(self,loc):
        ele = self.loc_ele(loc)
        ele.send_keys(Keys.CONTROL,'A')

    # 键盘事件-复制
    def selectcopy(self, loc):
        ele = self.loc_ele(loc)
        ele.send_keys(Keys.CONTROL, 'C')

    # 键盘事件-粘贴
    def selectzhan(self, loc):
        ele = self.loc_ele(loc)
        ele.send_keys(Keys.CONTROL, 'V')

    #切iframe
    def switchframe(self,loc):
        ele = self.loc_ele(loc)
        self.driver.switch_to.frame(ele)
    #退出iframe
    def backiframe(self):
        self.driver.switch_to.default_content()

    #切换窗口
    def switchwindow(self,n):
        self.driver.switch_to.window(self.driver.window_handles[n])

    #弹框处理
    def alert_ensure(self):
        self.driver.switch_to.alert.accept()

    #取消
    def alert_dismiss(self):
        self.driver.switch_to.alert.dismiss()

    #下拉框选择
    def selectitem(self,loc,index):
        ele = self.loc_ele(loc)
        Select(ele).select_by_index(index)